//切换条件维度事件
$("#customCode").bind("change", function(){
    $("#customValue option").remove();
    $("#s2id_customValue span:first").html("请选择"+$("#s2id_customCode span:first").html());
    var custom = $("#customCode").val();
    if(custom==''){
        $("#s2id_customValue span:first").html("");
        return
    }
    $("#customValue").append("<option value='' >"+$("#s2id_customCode span:first").html()+"</option>");
    $.ajax({
        url: "/map/customList",
        type: "POST",
        data: {'custom': custom} ,
        success: function(result){
            for(var i=0; i < result.customList.length; i++){
                var values =  result.customList[i].label;
                var define =  result.customList[i].define;
                var obj = document.createElement("option");
                obj.value = values;
                obj.innerHTML=values+" "+define;
                $("#customValue").append(obj);
            }
        }
    });

});
$("#customCode").change();
$("#city").bind("change", function(){
    $("#district option").remove();
    $("#s2id_district span:first").html("行政区");
    var city = $("#city").val()
    $("#district").append("<option value='-1' >行政区</option>")
    if(city=='-1'){
        return
    }
    $.ajax({
        url: "/estate/districtList",
        type: "POST",
        data: {'city': city} ,
        success: function(result){
            for(var i=0; i < result.districtList.length; i++){
                $("#district").append("<option value=" + result.districtList[i].zoneNumber + ">" + result.districtList[i].name + "</option>")
            }
        }
    });
    heatmap.reset({city:city,currentMap:'h  eatMap'});
});
//切换城市地图事件
function search(){
    //清空搜索
    $('#page').hide();
    $('#word2').hide();
    $("#search").val("");
    $('#searchCommunity').html("");
    $('#searchCommunity').css('display','none');
    $('#district').val("");
    $("#s2id_district span:first").html("行政区");
    $('#risk').val("");
    $("#s2id_risk span:first").html("押品风险");
    $('#startDateStart').val("");
    $('#startDateEnd').val("");
    $('#buildArea').val("");
    $("#s2id_buildArea span:first").html("面积区段");
    $('#loansDuration').val("");
    $("#s2id_loansDuration span:first").html("抵押年限");
    $('#customCode').val("");
    $("#s2id_customCode span:first").html("已抵押数量");
    $("#customValue option").remove();
    $("#s2id_customValue span:first").html("");
    var city = $("#city").val();
    heatmap.reset({city:city,currentMap:'heatMap'});
}
//find
function searchData(map){//搜索条件改变事件
    $('#word2').hide();
    //$('#searchCommunity').css('max-height','400px');
    $('#searchCommunity').css('display','block');
    var inputData = getInputData('heatMap');
    map.clearOverlays();
    if(currentMap=="pointMap"){
        pointOverlays.clearMarkers();
    }
    heatmap.reset(inputData);
    if(allMapData.length==0 || mapDataStatus==false){
        $('#searchCommunity').css('display','none');
        return
    }
    searchFlag=true;
    scrollFlag=false;
    map.centerAndZoom(new BMap.Point(allMapData[0].lng, allMapData[0].lat),16);
    searchCommunityResult("searchCommunity",allMapData);
    createCommunity(allMapData);
}
function getInputData(currentMap){
    var communityName=$("#search").val(),
        city=$('#city').val(),
        district=$('#district').val(),
        risk=$('#risk').val(),
        startDateStart = $('#startDateStart').val(),
        startDateEnd = $('#startDateEnd').val(),
        buildArea=$('#buildArea').val(),
        customCode=$('#customCode').val(),
        customValue=$('#customValue').val(),
        loansDuration=$('#loansDuration').val(),
        inputData={
            communityName:communityName,
            city:city,
            district:district,
            risk:risk,
            startDateStart:startDateStart,
            startDateEnd:startDateEnd,
            buildArea:buildArea,
            loansDuration:loansDuration,
            currentMap:currentMap,
            customCode:customCode,
            customValue:customValue
        };
    return inputData;
}
//参数改变事件
function searchData(map){//搜索条件改变事件
    $('#word2').hide();
    //$('#searchCommunity').css('max-height','400px');
    $('#searchCommunity').css('display','block');
    $('#page').show();
    var inputData = getInputData('heatMap');
    heatmap.reset(inputData);
    RequestData('/map/mapCommunityData',inputData);
    if(allMapData.length==0 || mapDataStatus==false){
        $('#searchCommunity').css('display','none');
        $('#page').hide();
        return
    }
    searchFlag=true;
    scrollFlag=false;
    searchCommunityResult("searchCommunity",allMapData);
}
function RequestData (url,paramsData) {
    $.ajax({
        type: "post",
        url: url,
        data: paramsData,
        async: false,
        success: function (data) {
            allMapData = data.result.mapDataList;
            mapDataStatus = data.result.mapDataStatus;
            // if (currentMap == "clusterMap") {
            //     boundaryData = data.result.boundaryList;
            // }
        }
    })
}
//小区搜索结果HTML
function searchCommunityResult(id,paramsData,flag){
    $('#'+id+'').css('display','block');
    var html='';
    var Count = paramsData.length;//记录条数
    var PageSize=5;//设置每页示数目
    var PageCount=Math.ceil(Count/PageSize);//计算总页数
    var currentPage =1;//当前页，默认为1。
    var price;
    if(Count < 5){
        PageSize=Count;//设置每页示数目
        PageCount=1;//计算总页数
    }
    // 分页
    $('#page').pagination({
        currentPage: 1,
        totalPage: PageCount,
        isShow: false,
        count: 6,
        prevPageText: "< 上一页",
        nextPageText: "下一页 >",
        callback: function (current) {
            //显示选择页的内容
            var selectPage=current;
            $('#searchCommunity li').remove();
            html = '';
            function size () {
                if(Count-(selectPage-1)*PageSize < 6){
                    return Count;
                }else{
                    return PageSize*selectPage;
                }
            }
            for(i=(selectPage-1)*PageSize;i<size();i++){
                price = (paramsData[i].price/10000).toFixed(2) + '万';
                html+=
                    "<li><h5></h5><div><a style='display: block;font-size: 14px;' href = 'javascript:centerCommunity("+JSON.stringify(paramsData[i])+","+flag+")'>"+paramsData[i].communityName+"</a><p style='color: #666; font-size: 12px; margin: 10px 0 0 0;'>金额 <span style='color:#FF0000'>"+price+"</span></p><p class='pull-left' style='color: #666;font-size: 12px;'>数量 <span style='color:#FF0000'>"+paramsData[i].count+"</span></p></div></li>";
            }
            $('#'+id+'').html(html);
            $('#'+id+' li').addClass('list-group-item media social-profile clearfix p-b-n');
            $('#'+id+' li h5').addClass('pull-left text-center p-n m-n');
            $('#'+id+' li div').addClass('media-body ');
        }
    });
    //显示默认页（第一页）
    for(var i=(currentPage-1)*PageSize;i<PageSize*currentPage;i++){
        //$('#table').append(paramsData[i]);
        price = (paramsData[i].price/10000).toFixed(2) + '万';
        html+=
            "<li><h5></h5><div><a style='display: block;font-size: 14px;' href = 'javascript:centerCommunity("+JSON.stringify(paramsData[i])+","+flag+")'>"+paramsData[i].communityName+"</a><p style='color: #666; font-size: 12px; margin: 10px 0 0 0;'>金额 <span style='color:#FF0000'>"+price+"</span></p><p class='pull-left' style='color: #666;font-size: 12px;'>数量 <span style='color:#FF0000'>"+paramsData[i].count+"</span></p></div></li>";
    }
    $('#'+id+'').html(html);
    $('#'+id+' li').addClass('list-group-item media social-profile clearfix p-b-n');
    $('#'+id+' li h5').addClass('pull-left text-center p-n m-n');
    $('#'+id+' li div').addClass('media-body ');
    $('#searchCommunity li div p:first').css('float ','right');

    /*$.each(paramsData,function(i,obj){
        console.log(obj)
        var communityName = obj.communityName;
        var count = obj.count;
        html+=
            "<li><h5>"+(i+1)+"</h5><div><a href = 'javascript:centerCommunity("+JSON.stringify(obj)+")'>"+communityName+"</a><p>数量"+count+"</p></div></li>";
    });
    $('#'+id+'').html(html);
    $('#'+id+' li').addClass('list-group-item media social-profile clearfix p-b-n');
    $('#'+id+' li h5').addClass('pull-left text-center p-n m-n');
    $('#'+id+' li div').addClass('media-body ');*/
    // 点击小区进入楼栋
    // $('#'+id+' a').click(function(event){
    //     event.preventDefault();
    //     var inputData = getInputData();
    //     inputData.communityId=$(this).attr("href");
    //     map.clearOverlays();
    //     scrollFlag=false;
    //     if(currentMap=="clusterMap"){
    //         RequestData("/map/mapBuildingBankData",inputData);
    //     }else{
    //         RequestData(buildingUrl,inputData);
    //     }
    //     map.centerAndZoom(new BMap.Point(Community.lng, Community.lat),19);
    //     if(currentMap=="clusterMap"){
    //         createBuilding_bank(allMapData,boundaryData,pt,"abc.png",Community.communityName,Community.communityId);
    //     }else{
    //         searchBuildingResult(id,allMapData);
    //         createBuilding(allMapData);
    //     }
    //
    // })
}
//楼栋搜索结果HTML
function searchBuildingResult(id,paramsData){
    $('#'+id+'').css('display','block');
    var html='';
    var i = 1;
    paramsData.forEach(function(data){
            var dkqs = "";
            var dkje = "";
            if(data.loansduration == null){
                dkqs = "--"
            }else{
                dkqs = data.loansduration
            }
            if(data.loansamount == null){
                dkje = "--"
            }else{
                dkje = data.loansamount
            }

            html+=     "<li><h5>"+(i++)+"</h5><div><a class='linkMap' id='"+data.id+"'>"+data.sourceaddress+"</a><p>贷款金额："+dkje+"元</p><p>放款日期："+data.startdate
                +" | 贷款期数："+dkqs+"期</p><p>当前评估价："+data.loansevaluatetotalprice+"元 | 动态抵押率："+data.cltv+"%</p></div></li>"
        // estateList.forEach(function(data){
        //     html+=     "<li><h5></h5><div><a class='linkMap' id='"+data.mortgageid+"'>"+data.sourceaddress+"</a><p>贷款金额："+data.loansamount+"元</p><p>放款日期："+data.startdate
        //         +" | 贷款期数："+data.loansduration+"期</p></div></li>"
        // })
    });
    $('#'+id+'').html(html);
    $('#'+id+' li').addClass('list-group-item media social-profile clearfix p-b-n');
    $('#'+id+' li h5').addClass('pull-left text-center p-n m-n');
    $('#'+id+' li div').addClass('media-body ');
    $('#'+id+' li p').addClass('m-n');
    $(".linkMap").click(function(){
        var href = window.location.origin + "/estate/mapShow/" + this.id;
        // var href = window.location.origin + "/mortgage/show/" + this.id;
        window.open(href);
    })
}
function centerCommunity(Community,flag){
    if(!flag)$('#page').hide();
    $('#search').val(Community.communityName);
    $('#word2').hide();
    $('#searchCommunity').css('display','block');
    var inputData = getInputData();
    inputData.communityId=Community.communityId;
    scrollFlag=false;
    currentMap = 'heatMap';
    if(currentMap=="clusterMap"){
            RequestData("/map/mapBuildingData2",inputData);
        }else{
            RequestData('/map/mapBuildingData2',inputData);
        }
    // if(currentMap=="clusterMap"){
    //     RequestData("/map/mapBuildingBankData3",inputData);
    // }else{
    //     RequestData('/map/mapBuildingBankData3',inputData);
    // }
        if(currentMap=="clusterMap"){
            createBuilding_bank(allMapData,boundaryData,pt,"abc.png",Community.communityName,Community.communityId);
        }else{
            searchBuildingResult("searchCommunity",allMapData);
            //createBuilding(allMapData);
        }
    heatmap.setRqCenter(Community,inputData);
}
function searchPicture(communityId){

    var purl="";
    var city = $("#city").val();
    $.ajax({
        type: "post",
        async: false,
        url: "/map/searchPicture",
        data: {
            communityId: communityId,
            city: city
        },
        success: function (data) {
            var pictureList=data.result.pictureList;
            var mapDataStatus = data.result.mapDataStatus;
            var length=pictureList.length;
            if(length==0 || mapDataStatus=='false'){
                purl="/assets/january.jpg"
            }else{
                purl=pictureList
            }
        }
    });
    return purl;
}
//页面参数
//小区联想搜索
//当键盘键被松开时发送Ajax获取数据
$('#search').keyup(function () {
    var paramsData = getInputData();
    var keywords = $(this).val();
    if (keywords == '') {
        $('#word2').hide();
        return
    };
    $.ajax({
        url: "/map/mapCommunityData",
        data:paramsData,
        dataType: 'json',
        type:"post",
        //jsonp: 'cb', //回调函数的参数名(键值)key
        // jsonpCallback: 'fun', //回调函数名(值) value
        beforeSend: function () {
            // $('#word').append('<div class="form-control">正在加载。。。</div>');
        },
        success: function (data) {
            $('#word2').empty().show();
            if (data.result.mapDataList.length==0 || data.result.mapDataList.mapDataStatus=="false") {
                $('#word2').append('<div class="error form-control">暂无相关数据</div>');
            }
            if(data.result.mapDataList.length<5){
                $.each(data.result.mapDataList, function (index,data) {
                    $('#word2').append("<a href = 'javascript:centerCommunity("+JSON.stringify(data)+")' class='click_work form-control' >"+data.communityName+"</a>");
                });
            }else{
                for(var i=0;i<5;i++){
                    $('#word2').append("<a href = 'javascript:centerCommunity("+JSON.stringify(data.result.mapDataList[i])+")' class='click_work form-control' >"+data.result.mapDataList[i].communityName+"</a>");
                }
            }
        },
        error: function () {
            $('#word2').empty().show();
            $('#word2').append('<div class="click_work form-control">Fail "' + keywords + '"</div>');
        }
    })
});
function getInputData(currentMap){
    var communityName=$("#search").val(),
        city=$('#city').val(),
        district=$('#district').val(),
        risk=$('#risk').val(),
        startDateStart = $('#startDateStart').val(),
        startDateEnd = $('#startDateEnd').val(),
        buildArea=$('#buildArea').val(),
        customCode=$('#customCode').val(),
        customValue=$('#customValue').val(),
        loansDuration=$('#loansDuration').val(),
        inputData={
            communityName:communityName,
            city:city,
            district:district,
            risk:risk,
            startDateStart:startDateStart,
            startDateEnd:startDateEnd,
            buildArea:buildArea,
            loansDuration:loansDuration,
            currentMap:currentMap,
            customCode:customCode,
            customValue:customValue
        };
    heatmap.inputData = inputData;
    return inputData;
}
function getDistrict(){
    $("#district option").remove();
    $("#s2id_district span:first").html("行政区");
    var city = $("#city").val()
    $("#district").append("<option value='-1' >行政区</option>")
    if(city=='-1'){
        return
    }
    $.ajax({
        url: "/estate/districtList",
        type: "POST",
        data: {'city': city} ,
        success: function(result){
            for(var i=0; i < result.districtList.length; i++){
                $("#district").append("<option value=" + result.districtList[i].zoneNumber + ">" + result.districtList[i].name + "</option>")
            }
        }
    });
}
//楼栋覆盖物
function createBuilding(paramsData,topmap){
    var target,topDiv,sj,lastSmall,oneSmall;
    paramsData.forEach(function (searchEstate) {
        searchEstate.forEach(function (data,i){
            //自定义楼栋覆盖物
            function ComplexCustomOverlay(point,num){
                this._point = point;
                this._num = num;
            }
            ComplexCustomOverlay.prototype = new BMap.Overlay();
            ComplexCustomOverlay.prototype.initialize = function(map){
                this._map = map;
                var smallDiv;
                if(i != 0){
                    if(oneSmall) oneSmall.style.padding = "6px 18px 6px 10px";
                    smallDiv = document.createElement('div');
                    smallDiv.appendChild(document.createTextNode(this._num));
                    smallDiv.style.padding = "6px 18px 6px 10px";
                    smallDiv.style.borderRadius = '8px';
                    smallDiv.style.marginLeft = '-10px';
                    if(data.estateList[0].define == '中风险'){
                        smallDiv.style.backgroundColor = "#FF9800";
                    }else if(data.estateList[0].define == '低风险'){
                        smallDiv.style.backgroundColor = "#62CB31";
                    }else if(data.estateList[0].define == '高风险'){
                        smallDiv.style.backgroundColor = "#E51C23";
                    }else if(data.estateList[0].define == '亏损'){
                        smallDiv.style.backgroundColor = "#8B1818";
                    }
                    lastSmall = smallDiv;
                    topDiv.appendChild(smallDiv);
                }else {
                    if(lastSmall) lastSmall.style.padding = '6px 10px';
                    var div = this._div = document.createElement("div");
                    div.style.position = "absolute";
                    div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);
                    div.style.color = "white";
                    div.style.opacity = '0.95';
                    div.style.display = 'flex';
                    div.style.whiteSpace = "nowrap";
                    div.style.MozUserSelect = "none";
                    div.style.fontSize = "12px";
                    div.style.cursor = "pointer";
                    smallDiv = document.createElement('div');
                    smallDiv.appendChild(document.createTextNode(this._num));
                    smallDiv.style.padding = "6px 10px";
                    smallDiv.style.borderRadius = "8px";
                    div.appendChild(smallDiv);
                    sj = this._p = document.createElement("p");
                    if(data.estateList[0].define == '中风险'){
                        smallDiv.style.backgroundColor = "#FF9800";
                        sj.style.borderTop = "10px solid #FF9800";
                    }else if(data.estateList[0].define == '低风险'){
                        smallDiv.style.backgroundColor = "#62CB31";
                        sj.style.borderTop = "10px solid #62CB31";
                    }else if(data.estateList[0].define == '高风险'){
                        smallDiv.style.backgroundColor = "#E51C23";
                        sj.style.borderTop = "10px solid #E51C23";
                    }else if(data.estateList[0].define == '亏损'){
                        smallDiv.style.backgroundColor = "#8B1818";
                        sj.style.borderTop = "10px solid #8B1818";
                    }
                    sj.style.position = "absolute";
                    sj.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);
                    sj.style.width = 0;
                    sj.style.height = 0;
                    sj.style.borderLeft = "10px solid transparent";
                    sj.style.borderRight = "10px solid transparent";
                    sj.style.bottom = "-20px";
                    sj.style.left = '6px';
                    div.appendChild(sj);
                    oneSmall = smallDiv;
                    lastSmall = null;
                    topDiv = div;
                }
                topDiv.onclick = function () {
                    $(this).siblings("div").children("div.row").css("display","none");
                    $(this).siblings("div").css('zIndex','-11');
                    $(this).css('zIndex','11')
                    $(this).children('div.row').toggle();
                    if($(this).children('div.row').length >= 1) return;
                    var listDiv = document.createElement("div");
                    listDiv.style.position = 'absolute';
                    listDiv.style.left = this.offsetWidth + 14 + "px";
                    listDiv.style.color = '#6a6c6f';
                    listDiv.style.width = '400px';
                    listDiv.style.whiteSpace = 'normal';
                    listDiv.className = 'row';
                    var col = document.createElement("div");
                    var hpanel = document.createElement("div");
                    hpanel.className = 'hpanel';
                    var hpanelHead = document.createElement("div");
                    hpanelHead.className = 'panel-heading hbuilt';
                    hpanelHead.onclick = function (e) {
                        e.stopPropagation()
                    };
                    listDiv.onmouseenter = function () {
                        topmap.disableScrollWheelZoom();
                    };
                    listDiv.onmouseleave = function () {
                        topmap.enableScrollWheelZoom();
                    };
                    var panelTools = document.createElement('div');
                    panelTools.className = 'panel-tools';
                    var closebox = document.createElement('a');
                    var closeIcon = document.createElement('i');
                    closeIcon.className = 'fa fa-times';
                    closebox.appendChild(closeIcon);
                    closebox.className = 'closebox';
                    var that = $(this);
                    closebox.onclick = function () {
                        that.children("div.row").css("display","none");
                    };
                    panelTools.appendChild(closebox);
                    hpanelHead.appendChild(panelTools);
                    hpanelHead.appendChild(document.createTextNode(data.estateList[0].communityname));
                    var hpanelBody = document.createElement("div");
                    hpanelBody.className = 'panel-body no-padding';
                    hpanelBody.style.maxHeight = '190px';
                    hpanelBody.style.overflowY = 'auto';
                    var listGroup = document.createElement('ul');
                    listGroup.className = 'list-group';
                    var hpanelFoot = document.createElement('div');
                    hpanelFoot.className = 'panel-footer';
                    hpanelBody.appendChild(listGroup);
                    hpanel.appendChild(hpanelHead);
                    hpanel.appendChild(hpanelBody);
                    hpanel.appendChild(hpanelFoot);
                    col.appendChild(hpanel);
                    listDiv.appendChild(col);
                    this.appendChild(listDiv);
                    searchEstate.forEach(function(data){
                        var itemData = data.estateList;
                        itemData.forEach(function (data) {
                            var item = document.createElement('li');
                            item.className = 'list-group-item ';
                            var badge = document.createElement('span');
                            badge.className = 'badge badge-info';
                            badge.innerHTML = data.cltv + '%';
                            item.appendChild(badge);
                            if(data.define == '中风险'){
                                badge.style.backgroundColor = "#FF9800";
                            }else if(data.define == '低风险'){
                                badge.style.backgroundColor = "#62CB31";
                            }else if(data.define == '高风险'){
                                badge.style.backgroundColor = "#E51C23";
                            }else if(data.define == '亏损'){
                                badge.style.backgroundColor = "#8B1818";
                            }
                            item.appendChild(document.createTextNode(data.sourceaddress));
                            item.onclick = function () {
                                var href = window.location.origin + "/estate/mapShow/" + data.id;
                                window.open(href);
                            };
                            listGroup.appendChild(item);
                        });
                    });
                    var listLength = listGroup.children.length;
                    hpanelFoot.innerHTML = '共 '+listLength+' 笔';
                };
                map.getPanes().labelPane.appendChild(topDiv);
                return topDiv;
            };
            ComplexCustomOverlay.prototype.draw = function(){
                var map = this._map;
                var pixel = map.pointToOverlayPixel(this._point);
                if(i != 0){
                    topDiv.style.left = pixel.x + (i * target -1) + "px";
                }else {
                    target = this._div.offsetWidth;
                    topDiv.style.left = pixel.x + "px";
                }
                topDiv.style.top  = pixel.y + "px";
            };
            var pt = new BMap.Point(data.estateList[0].lng,data.estateList[0].lat);
            var areaResult = data.estateList.length + "笔";
            myCompOverlay = new ComplexCustomOverlay(pt, areaResult);
            map.addOverlay(myCompOverlay);
        });
    });
    scrollFlag = true;
}